import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'aikit_plugin_platform_interface.dart';

/// An implementation of [AikitPluginPlatform] that uses method channels.
class MethodChannelAikitPlugin extends AikitPluginPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('aikit_plugin');
  static const EventChannel _eventChannel = EventChannel('aikit_plugin_stream');

  final Stream<Map<String, Object>> _onGetResult = _eventChannel
      .receiveBroadcastStream()
      .asBroadcastStream()
      .map<Map<String, Object>>((element) => element.cast<String, Object>());

  StreamController<TransResult>? _receiveStream;
  StreamSubscription<Map<String, Object>>? _subscription;

  @override
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  Future<String?> initSDK(String APPID, String APIKEY, String APISECRET) async {
    final msg = await methodChannel.invokeMethod<String>('initSDK',{'APPID':APPID,'APIKEY':APIKEY,'APISECRET':APISECRET});
    return msg;
  }

  @override
  Future<String?> startRecord(String keyword) async {
    final msg = await methodChannel.invokeMethod<String>('startRecord',{'keyword':keyword});
    return msg;
  }

  @override
  Future<String?> stopRecord() async {
    // TODO: implement stopRecord
    final msg = await methodChannel.invokeMethod<String>('stopRecord');
    return msg;
  }

  /// 获取结果流
  @override
  Stream<TransResult> onResult() {
    if (_receiveStream == null) {
      _receiveStream = StreamController();
      _subscription = _onGetResult.listen((Map<String, Object> event) {
        print('event----'+ event.toString());
        Map<String, Object> newEvent = Map<String, Object>.of(event);
        _receiveStream?.add(TransResult.fromMap(newEvent));
      });
    }
    return _receiveStream!.stream;
  }
}
class TransResult {
  TransResult(
      {
        required this.result,
        required this.code,
        required this.success,
        required this.type
      });
  factory TransResult.fromMap(Map<dynamic, dynamic> map) => TransResult(
    result: map['result'],
    code: map['code'],
    success: map['success'],
    type: map['type'],
  );
  final String result;
  final String code;
  final bool success;
  final String type;
}